package com.code.generator.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import com.code.generator.ExceputionUtils;
import com.code.generator.db.ConnectionFactory;
import com.code.generator.entity.ColumnsEntity;
import com.code.generator.entity.TableEntity;
import com.code.plugin.MessagesProperties;
import com.code.view.entity.HandlerVO;


/**
 * 获取数据库表结构信息
 *
 *
 * @author 朱国军
 * @version 2014年8月25日 朱国军
 */
public class TableInfoService {

    /**
     * 获取数据库表结构信息
     *
     * @param tableName 数据库表名
     * @param handlerVO 界面上配置的配置信息
     *
     * @return 数据库表结构数据
     */
    public TableEntity queryTableInfo(String tableName, HandlerVO handlerVO) {
        ConnectionFactory dbConnection = new ConnectionFactory(handlerVO.getDbDriver());
        String dbUserName = handlerVO.getDbUserName();
        TableEntity tableEntity = null;
        List<ColumnsEntity> columnsEntitys = null;
        Connection conn = null;
        try {
            conn = dbConnection.getConnection(dbUserName, handlerVO.getDbPassword(), handlerVO.getDbDriver(), handlerVO.getDbUrl());
        } catch (Exception e) {
            ExceputionUtils.logging(MessagesProperties.exception_get_connection, e);
        }
        if (conn != null) {
            try {
                tableEntity = dbConnection.getTableEntity(conn, tableName);
            } catch (Exception e) {
                ExceputionUtils.logging(MessagesProperties.exception_get_table_info, e);
            }
            try {
                columnsEntitys = dbConnection.getColumnsEntity(conn, tableName, dbUserName);
            } catch (Exception e) {
                ExceputionUtils.logging(MessagesProperties.exception_get_column_info, e);
            }
            if (tableEntity != null && columnsEntitys != null) {
                tableEntity.setColumnsEntitys(columnsEntitys);
            }
        }
        try {
            if (conn != null) {
                conn.close();
                conn = null;
            }
        } catch (SQLException e) {
            ExceputionUtils.logging(MessagesProperties.exception_close_connection, e);
        }

        return tableEntity;
    }
}
